//Copyright (c) Microsoft Corporation.  All rights reserved.

using System;
using System.Collections.Generic;
using System.Text;

namespace Eas.WebCrawler.PlugIns.FileNamers {
    /// <summary>Creates a filename only out of the page portion of the <see cref="Uri"/>.</summary>
    /// <remarks>This class creates a filename out of the <see cref="Uri"/> in the passed in <see cref="Eas.WebCrawler.Interfaces.Request"/> by striping off the protocol (i.e. http://), the host name and path and then replacing all invalid characters in the <see cref="Uri"/> (including the path seperator) with underscores.
    /// Duplicates are handled by appending _1, _2 ...    
    /// This class differs from the <see cref="FullUrlNamer"/> in that this class will not include the host name directory structure in the resulting file name.</remarks>
    /// <example>The url http://www.erik.com/saltwell/default.html will return default.html if no other file of that name exists in the base directory.</example>
    public class SimpleUrlNamer : FileNamer{
        #region FileNamer Members

        /// <summary>Returns the name of a non-existant file in the passed-in <paramref name="baseDirectory"/>.</summary>
        /// <param name="request">The <see cref="Eas.WebCrawler.Interfaces.Request"/> for which a file name should be created.</param>
        /// <param name="baseDirectory">The directory into which the file will be saved.</param>
        /// <returns>The document name portion of the <see cref="Uri"/> of the <paramref name="request"/> with all invalid characters and path seperators replaced by underscores.</returns>
        public string GetFileName(Eas.WebCrawler.Interfaces.Request request, System.IO.DirectoryInfo baseDirectory) {
            string originalPath = NameHelper.EscapeFileName(GetDocument(request.Uri));
            return NameHelper.AppendFileNumber(originalPath, baseDirectory);
        }

        #endregion

        private static string GetDocument(Uri uri) {
            string last = uri.Segments[uri.Segments.Length - 1];
            if (last.IndexOf("/", StringComparison.Ordinal) == -1 && last.IndexOf(".", StringComparison.Ordinal) != -1)
                return last;
            else
                return "Default.html";
        }


        #region WebCrawlerComponent Members
        /// <summary>Initializes this class</summary>
        /// <param name="context">The <see cref="Eas.WebCrawler.Interfaces.WebCrawlerContext"/> which will contain data about this instance of the web crawler.</param>
        public void Initialize(Eas.WebCrawler.Interfaces.WebCrawlerContext context) { }
        #endregion
    }
}
